//
//  CreateViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/4/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "CreateViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "InviteFriendViewController.h"
#import "CreateEventCell.h"
#import "EventDetailViewController.h"
#import "GruphotoAppDelegate.h"
#import "User.h"
#import "Event.h"

#define ALPHA_LC        @"abcdefghijklmnopqrstuvwxyz"
#define ALPHA_UC        [ALPHA_LC uppercaseString]
#define NUMBERS         @"0123456789"
#define PUNCTUATION     @"~!@#$%^&*+=?/|:;"

#define kLabelTag       4096
#define kLabelDetailTag 4095
#define kTitleTextFieldTag  95
#define kPhoneTextFieldTag  96

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"background_navigation_bar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

@interface CreateViewController (PrivateMethods)
- (void)addBarItems;
- (NSString *)generateRandomCode;
@end

@implementation CreateViewController
@synthesize eventTableView, eventScrollView, placeAddressLabel;
@synthesize headerView, placeNameLabel, placeType;
@synthesize place;
@synthesize isPrivate, textFieldBeingEdited, editMode;
@synthesize eventTitle, eventEnd, phoneNumber, code, eventEndString;

#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"background_navigation_bar.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
    }
    [self addBarItems];
    headerView.layer.borderWidth = 1;
    headerView.layer.borderColor = [UIColor colorWithRed:178/255.0 green:182/255.0 blue:186/255.0 alpha:1.0].CGColor;
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    eventScrollView.contentSize = CGSizeMake(320, eventScrollView.frame.size.height + 220);
    placeNameLabel.textColor = [UIColor colorWithRed:107/255.0 green:120/255.0 blue:130/255.0 alpha:1.0];
    eventTableView.backgroundColor = [UIColor clearColor];
    eventTableView.opaque = NO;
    isPrivate = NO;
    self.eventTitle = @"";
    self.eventEnd = 24;
    self.eventEndString = @"24h";
    self.phoneNumber = @"";
    self.code = [self generateRandomCode];
    
    if (placeType == GPPlaceTypeUnknow && editMode == EventEditModeCreate) {
        placeNameLabel.textColor = [UIColor colorWithRed:71/255.0 green:138/255.0 blue:197/255.0 alpha:1.0];
        placeNameLabel.text = @"Outdoor (unknown place)";
    }
    else {
        placeNameLabel.text = [place objectForKey:@"name"];
    }
    placeAddressLabel.text = [[place objectForKey:@"location"] objectForKey:@"street"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.eventTableView = nil;
    self.headerView = nil;
    self.placeNameLabel = nil;
    self.eventScrollView = nil;
    self.placeAddressLabel = nil;
}

- (void)dealloc {
    self.place = nil;
    self.eventTitle = nil;
    self.phoneNumber = nil;
    self.code = nil;
    self.textFieldBeingEdited = nil;
    self.eventEndString = nil;
    [eventScrollView release];
    [eventTableView release];
    [headerView release];
    [placeNameLabel release];
    [placeAddressLabel release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private methods
- (void)addBarItems {
    UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title_gruphoto.png"]];
    self.navigationItem.titleView = titleImageView;
    [titleImageView release];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setBounds:CGRectMake(0, 0, 51, 30)];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"button_cancel.png"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
    self.navigationItem.leftBarButtonItem = cancelButtonItem;
    [cancelButtonItem release];

    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [editButton setBounds:CGRectMake(0, 0, 51, 30)];
    if (editMode == EventEditModeCreate) {
        [editButton setBackgroundImage:[UIImage imageNamed:@"button_create.png"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(createButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    else { // Edit mode update
        [editButton setBackgroundImage:[UIImage imageNamed:@"button_done.png"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }    
    UIBarButtonItem *editButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
    self.navigationItem.rightBarButtonItem = editButtonItem;
    [editButtonItem release];
}

- (NSString *)generateRandomCode {
    NSString *selectedSet = ALPHA_UC;
    selectedSet = [selectedSet stringByAppendingString:NUMBERS];
    
    NSString *result = @"";
    NSRange range;
    range.length = 1;
    
    int targetLength = 8;
    int i;
    for (i = 0; i < targetLength; i++) {
        range.location = random() % [selectedSet length];
        result = [result stringByAppendingString:[selectedSet substringWithRange:range]];
    }
    return result;
}

#pragma mark - Action methods
- (IBAction)cancelButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)createButtonPressed:(id)sender {
    if (textFieldBeingEdited != nil) {
        if (textFieldBeingEdited.tag == kTitleTextFieldTag) {
            self.eventTitle = textFieldBeingEdited.text;
        }
        else if (textFieldBeingEdited.tag = kPhoneTextFieldTag) {
            self.phoneNumber = textFieldBeingEdited.text;
        }
        [textFieldBeingEdited resignFirstResponder];
    }
    
    // Validate data    
    NSString *errorMessage = nil;
    
    if (eventTitle.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter event title", @"");
    }

    if (errorMessage != nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error message", @"")
                                                            message:errorMessage
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
        return;
    }
    
    
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Creating..."];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
    [params setObject:eventTitle forKey:kTitle];
    [params setObject:[NSString stringWithFormat:@"%d", eventEnd] forKey:kTimeLimit];
    FBGraphObject *location = [place objectForKey:@"location"];
    [params setObject:[location objectForKey:@"latitude"] forKey:kLatitude];
    [params setObject:[location objectForKey:@"longitude"] forKey:kLongitude];
    [params setObject:[place objectForKey:@"name"] forKey:kPlaceName];
    [params setObject:[location objectForKey:@"street"] forKey:kPlaceAddress];
    [params setObject:phoneNumber forKey:kPhone];
    [params setObject:code forKey:kCode];
    [params setObject:[NSNumber numberWithBool:!isPrivate] forKey:kIsPublic];
    [params setObject:@"Gruphoto event" forKey:kDescription];
    NSLog(@"params: %@", params);
    [TNHRequestHelper sendPostRequest:kCreateEventUrl
                              withTag:RequestTagCreateEvent
                               params:params
                             delegate:self];
}

- (IBAction)doneButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)switchValueChanged:(id)sender {
    UISwitch *switcher = (UISwitch *)sender;
    isPrivate = switcher.isOn;
    if (isPrivate) {
        self.code = [self generateRandomCode];
    }
    [eventTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.2];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == kTitleTextFieldTag) {
        self.eventTitle = textField.text;
    }
    else if (textField.tag = kPhoneTextFieldTag) {
        self.phoneNumber = textField.text;
    }
    [textField resignFirstResponder];
    [eventScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == kTitleTextFieldTag) {
        self.eventTitle = textField.text;
    }
    else if (textField.tag = kPhoneTextFieldTag) {
        self.phoneNumber = textField.text;
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.textFieldBeingEdited = textField;
    float yOffset = 0;
    if (![Global isIphone5]) {
        yOffset = 10;
    }
    if (textField.tag == kPhoneTextFieldTag) {
        yOffset = 140;
    }
    [eventScrollView setContentOffset:CGPointMake(0, yOffset) animated:YES];
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"Event Details";
    }
    return @"Event Secure";
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        if (!isPrivate) {
            return 60;
        }
        return 40;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UILabel *footer = [[UILabel alloc] init];
        footer.font = [UIFont fontWithName:@"MyriadPro-Regular" size:16];
        footer.textColor = [UIColor colorWithRed:76/255.0 green:86/255.0 blue:108/255. alpha:1.0];
        footer.backgroundColor = [UIColor clearColor];
        footer.textAlignment = UITextAlignmentCenter;
        footer.lineBreakMode = UILineBreakModeWordWrap;
        if (!isPrivate) {
            footer.frame = CGRectMake(0, 0, 320, 60);
            footer.numberOfLines = 2;
            footer.text = @"Enable Private Event mode will activate randomly secure code for potential users";
        }
        else {
            footer.frame = CGRectMake(0, 0, 320, 40);
            footer.numberOfLines = 1;
            footer.text = @"You’ve been activated the Private event\n";
        }
        return [footer autorelease];
    }
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        if (isPrivate) {
            return 2;
        }
        return 1;
    }
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CreateEventCell *cell = nil;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                cell = [CreateEventCell titleCellFromNib];
                cell.textField.delegate = self;
                cell.textField.text = eventTitle;                
                if (textFieldBeingEdited == cell.textField) {
                    self.textFieldBeingEdited = nil;
                }
                break;
            case 1:
                cell = [CreateEventCell indicatorCellFromNib];
                cell.label.text = @"Event end";
                cell.detailLabel.text = eventEndString;
                break;
            case 2:
                cell = [CreateEventCell indicatorCellFromNib];                
                cell.label.text = @"Invite friends";
                cell.detailLabel.hidden = YES;
                break;
            case 3:
                cell = [CreateEventCell phoneCellFromNib];
                cell.textField.delegate = self;
                cell.textField.text = phoneNumber;
                if (textFieldBeingEdited == cell.textField) {
                    self.textFieldBeingEdited = nil;
                }
                break;
            default:
                break;
        }
    }
    else {
        if (indexPath.row == 0) {
            cell = [CreateEventCell switcherCellFromNib];
            [cell.switcher addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
            [cell.switcher setOn:isPrivate];
        }
        else {
            cell = [CreateEventCell codeCellFromNib];
            cell.detailLabel.text = code;
        }
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [eventTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 2) {
            InviteFriendViewController *inviteFriendViewController = [[InviteFriendViewController alloc] initWithNibName:@"InviteFriendViewController" bundle:nil];
            inviteFriendViewController.isPrivate = isPrivate;
            inviteFriendViewController.code = code;
            [self.navigationController pushViewController:inviteFriendViewController animated:YES];
            [inviteFriendViewController release];
        }
    }
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    NSLog(@"response: %@", request.responseString);
    if (request.tag == RequestTagCreateEvent) {
        NSDictionary *response = (NSDictionary *)[TNHRequestHelper objectWithString:request.responseString];
        NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
        if (errorCode == ErrorCodeNone) {
            Event *createdEvent = [[Event alloc] init];
            createdEvent.eventId = [[response objectForKey:kEventId] integerValue];
            createdEvent.eventTitle = [response objectForKey:kTitle];
            createdEvent.description = [response objectForKey:kDescription];
            createdEvent.placeName = [place objectForKey:@"name"];
            createdEvent.placeAddress = [[place objectForKey:@"location"] objectForKey:@"street"];
            createdEvent.longitude = [response objectForKey:kLongitude];
            createdEvent.latitude = [response objectForKey:kLatitude];
            createdEvent.eventEnd = [[response objectForKey:kTimeLimit] integerValue];
            createdEvent.isPrivate = isPrivate;
            createdEvent.code = code;
            createdEvent.creater = [GruphotoAppDelegate sharedDelegate].loggedInUser;
            
            EventDetailViewController *eventDetailViewController = [[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil];
            eventDetailViewController.detailMode = EventDetailModeCreate;
            eventDetailViewController.event = createdEvent;
            [createdEvent release];
            
            [self.navigationController pushViewController:eventDetailViewController animated:YES];
            NSArray *viewControllers = [NSArray arrayWithObject:[self.navigationController.viewControllers lastObject]];
            [self.navigationController setViewControllers:viewControllers animated:NO];
            [eventDetailViewController release];            
        }
        else {
            NSString *errorMessage = [response objectForKey:kErrorMessage];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error message"
                                                                message:errorMessage
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                        message:@"Internet is down, please try again"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

@end